package com.learn.service;

import com.alibaba.fastjson.JSON;
import com.learn.pojo.Content;
import com.learn.utils.HtmlParseUtil;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class ContentService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    public Boolean parseContent(String keywords) throws Exception{
        List<Content> contentList = HtmlParseUtil.parseJD(keywords);

        BulkRequest bulkRequest = new BulkRequest();

        contentList.forEach(list ->
                        bulkRequest.add(new IndexRequest("jd-goods").id(UUID.randomUUID().toString()).source(JSON.toJSONString(list), XContentType.JSON))
                );

        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);

        return !bulk.hasFailures();
    }

    public List<Map<String, Object>> searchPage(String keyword, int startPageNum, int pageSize)throws Exception{
        if(startPageNum < 1){
            startPageNum = 1;
        }

        //条件搜索
        SearchRequest searchRequest = new SearchRequest("jd-goods");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.requireFieldMatch(false); //多个高亮显示！
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);

        //搜索方式
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("title", keyword);
        searchSourceBuilder.query(matchQueryBuilder);
        searchRequest.source(searchSourceBuilder);

        //分页
        searchSourceBuilder.from(startPageNum);
        searchSourceBuilder.size(pageSize);

        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        List<Map<String, Object>> list = new ArrayList<>();

        for (SearchHit hit : search.getHits().getHits()) {

            Map<String, Object> sourceAsMap = hit.getSourceAsMap();

            //将高亮搜索从查询的数据中心替换掉
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField title = highlightFields.get("title");
            if(title != null){
                Text[] fragments = title.fragments();
                String n_title = "";
                for (Text text : fragments) {
                    n_title += text;
                }
                sourceAsMap.put("title", n_title);
            }

            list.add(sourceAsMap);
        }

        return list;
    }

}
